#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include "pcm.h"
#include <pthread.h>

using namespace std;
bool g_pause;
int msgid=-1;
int res;
pthread_mutex_t pause_mutex;
int pause_time;
int sum=0;

void * receive(void* arg);

int main(int argc, char * argv[])
{
	bool pause_local=false;
	pthread_t a_thread;
	msgid=msgget(KEY,0666|IPC_CREAT);
	if(msgid<0)
	{
		perror("failed to create a message queue\n");
		return 0;
	}
	res=pthread_create(&a_thread,NULL, receive, (void*)0);
	cout<<"lyric   "<<argc<<endl<<argv[1]<<endl;
	char str[100];	
	int now,last=0;
	char i='1';	
	FILE *fp=fopen(argv[1],"r");
	struct timeval start;
	struct timeval end;	
	struct timeval start1;
	struct timeval end1;	
	if(fp==NULL)
	{
		perror("fail to open");
		return 0;
	}	
	gettimeofday(&start,NULL);	
	while(!feof(fp) && !ferror(fp))
	{
		fgets(str,sizeof(str),fp);
		now=((str[1]-48)*10+str[2]-48)*60+(str[4]-48)*10+str[5]-48;
		//gettimeofday(&start1,NULL);	
		//usleep((now-last)*1000000);
		//gettimeofday(&end1,NULL);
		//cout<<"sleep time"<<end1.tv_sec-start1.tv_sec<<endl;
		gettimeofday(&end,NULL);
		while(((end.tv_sec-start.tv_sec)*1000000+end.tv_usec-start.tv_usec-sum)<now*1000000||g_pause)
		{
			usleep(100);
			gettimeofday(&end,NULL);
		}
		cout<<"sum in main:"<<(double)sum/1000000<<endl;
		cout<<str<<endl;
	}
	fclose(fp);
	return 0;
}

void *receive(void *arg)
{
	struct timeval start2={0,0};
	struct timeval end2={0,0};
	cout<<"in the thread"<<endl;
	Mymsg mymsg;
	int nbytes=0;
	while(true)
	{
		msgrcv(msgid,&mymsg,nbytes,0,0);
		if(mymsg.mytype==PAUSE)
		{
			if(g_pause)
			{
				continue;
			}
			pthread_mutex_lock(&pause_mutex);
			gettimeofday(&start2,NULL);
			g_pause=true;
			pthread_mutex_unlock(&pause_mutex);
			cout<<"pause"<<endl;
		}
		else if(mymsg.mytype==RESUME)
		{
			if(!g_pause)
			{
				continue;
			}
			pthread_mutex_lock(&pause_mutex);
			gettimeofday(&end2,NULL);
			pause_time=(end2.tv_sec-start2.tv_sec)*1000000+end2.tv_usec-start2.tv_usec;
			cout<<"pause_time:"<<(double)pause_time/1000000<<endl;
			sum+=pause_time;
			cout<<"sum:"<<(double)sum/1000000<<endl;
			g_pause=false;
			pthread_mutex_unlock(&pause_mutex);
			cout<<"resume"<<endl;
		}
		else if(mymsg.mytype==EXIT)
		{
			cout<<"exiting"<<endl;
			exit(0);
		}
	}
}
	
	
	
